package com.cskaoyan.service;

import com.cskaoyan.bean.data.PageData;
import com.cskaoyan.mapper.MarketRegionMapper;
import com.cskaoyan.model.MarketRegion;
import com.cskaoyan.model.MarketRegionExample;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class RegionServiceImpl implements RegionService {
    @Autowired
    MarketRegionMapper regionMapper;

    @Override
    public PageData selectAll() {
        MarketRegionExample example = new MarketRegionExample();
        example.createCriteria().andTypeEqualTo((byte) 1);
        List<MarketRegion> provinceList = regionMapper.selectByExample(example);
        example.clear();
        example.createCriteria().andTypeEqualTo((byte) 2);
        List<MarketRegion> cityList = regionMapper.selectByExample(example);
        example.clear();
        example.createCriteria().andTypeEqualTo((byte) 3);
        List<MarketRegion> areaList = regionMapper.selectByExample(example);


        Map<Integer, List<MarketRegion>> cityIdAreaListMap = areaList.stream().collect(Collectors.groupingBy(MarketRegion::getPid));
        cityList.forEach(city -> {
            city.setChildren(cityIdAreaListMap.get(city.getId()));
        });

        Map<Integer, List<MarketRegion>> provinceIdCityListMap = cityList.stream().collect(Collectors.groupingBy(MarketRegion::getPid));
        provinceList.forEach(province -> {
            province.setChildren(provinceIdCityListMap.get(province.getId()));
        });


        return PageData.list(provinceList);
    }
}
